package com.huiyan.hysys.service.impl;

import com.huiyan.hysys.config.RedisKeyConfig;
import com.huiyan.hysys.config.SystemConfig;
import com.huiyan.hysys.dao.OssLogDao;
import com.huiyan.hysys.entity.OssLog;
import com.huiyan.hysys.service.intf.OssLogService;
import com.huiyan.hysys.third.AliOssUtil;
import com.huiyan.hysys.third.JedisUtil;
import com.huiyan.hysys.util.DateUtil;
import com.huiyan.hysys.util.FileUtil;
import com.huiyan.hysys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;


@Service
public class OssLogServiceImpl implements OssLogService {
    @Autowired
    private OssLogDao dao;
    @Override
    public R upload(MultipartFile file, String token) {
        //1.校验令牌
        if(JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN+token)){
            //校验文件
            if(!file.isEmpty()){
                //文件名重命名并保证长度
                String objName= FileUtil.rename(file.getOriginalFilename());
                //获取链接有效期
                Date date= DateUtil.getDate(SystemConfig.OSS_URL_DAYS);
                try{
                    //将资源上传到阿里云-oss服务器
                    String url= AliOssUtil.upload(objName,date,file.getInputStream());
                    //校验
                    if(StringUtils.hasLength(url)){
                        //上传成功 记录到数据库
                        OssLog log=new OssLog(SystemConfig.OSS_1, AliOssUtil.bucket,objName,url,new Date(),date);
                        dao.insert(log);

                        return R.ok(log);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return R.fail();
    }

    @Override
    public R all() {
        return R.ok(dao.selectList(null));
    }
}
